package com.epoch.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.epoch.base.annotation.ControllerBind;
import com.epoch.bussiness.wxuser.dao.WxUserDao;
import com.epoch.wx.annotaion.IgnoreAuth;
import com.epoch.wx.base.ApiBaseController;
import com.epoch.wx.entity.FullUserInfo;
import com.epoch.wx.entity.UserInfo;
import com.epoch.wx.service.TokenService;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import me.chanjar.weixin.common.error.WxErrorException;

@ControllerBind(controllerKey = "/api/auth")
public class ApiLoginController extends ApiBaseController{
	
	protected Logger logger = LoggerFactory.getLogger(ApiLoginController.class);

	@IgnoreAuth
	public void login() {
		JSONObject jsonParam = this.getJsonRequest();
		FullUserInfo fullUserInfo = null;
        String code = "";
        if (!StringUtils.isEmpty(jsonParam.getString("code"))) {
            code = jsonParam.getString("code");
        }
        if (null != jsonParam.get("userInfo")) {
            fullUserInfo = jsonParam.getObject("userInfo", FullUserInfo.class);
        } 
        Map<String, Object> resultObj = new HashMap<String, Object>();
        //
        UserInfo userInfo = fullUserInfo.getUserInfo();
        try {
			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
			// 用户信息校验
	        if (!wxMaService.getUserService().checkUserInfo(session.getSessionKey(), fullUserInfo.getRawData(), fullUserInfo.getSignature())) {
	        	renderJson(toResponsFail("登陆失败，用户信息不完整!"));
	        }
	        WxUserDao wxUser = WxUserDao.dao.findFirst("select * from wx_user where openid = ?", session.getOpenid());
	        if(null == wxUser) {
	        	wxUser = new WxUserDao();
	        	wxUser.set(WxUserDao.OPENID, session.getOpenid());
	        	wxUser.set(WxUserDao.NICKNAME, userInfo.getNickName());
	        	wxUser.set(WxUserDao.AVATARURL, userInfo.getAvatarUrl());
	        	wxUser.set(WxUserDao.GENDER, userInfo.getGender());
	        	wxUser.set(WxUserDao.REGISTER_TIME, new Date());
	        	wxUser.set(WxUserDao.LAST_LOGIN_IP, getClientIp());
	        	wxUser.set(WxUserDao.LAST_LOGIN_TIME, new Date());
	        	wxUser.set(WxUserDao.PROVINCE, userInfo.getProvince());
	        	wxUser.set(WxUserDao.CITY, userInfo.getCity());
	        	wxUser.save();
	        }
	        Map<String, Object> tokenMap= TokenService.me.createToken(wxUser.getStr(WxUserDao.ID));
	        String token = MapUtils.getString(tokenMap, "token");
	        resultObj.put("token", token);
	        resultObj.put("userInfo", userInfo);
	        resultObj.put("userId", wxUser.getStr(WxUserDao.ID));
	        resultObj.put("openid", session.getOpenid());
	        resultObj.put("username", userInfo.getNickName());
	        renderJson(toResponsSuccess(resultObj));
        } catch (WxErrorException e) {
			this.logger.error(e.getMessage(), e);
			renderJson(toResponsFail("登陆失败!"));
		}
	        
	}
}
